package com.sls.nzdapplication.ui.activity;

import static com.hjq.permissions.XXPermissions.REQUEST_CODE;
import static com.huawei.hms.feature.DynamicModuleInitializer.getContext;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import com.esri.arcgisruntime.geometry.Point;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.concurrent.ListenableFuture;

import com.esri.arcgisruntime.geometry.PolylineBuilder;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.layers.WebTiledLayer;
import com.esri.arcgisruntime.location.LocationDataSource;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.GeoElement;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.IdentifyGraphicsOverlayResult;
import com.esri.arcgisruntime.mapping.view.LocationDisplay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.sls.nzdapplication.R;
import com.sls.nzdapplication.app.MySharedPreferences;
import com.sls.nzdapplication.db.utils.EquipmentLineUtil;
import com.sls.nzdapplication.db.utils.EquipmentUtil;
import com.sls.nzdapplication.db.utils.GyyhdUtil;
import com.sls.nzdapplication.model.Equipment;
import com.sls.nzdapplication.model.EquipmentLine;
import com.sls.nzdapplication.model.Gyyhd;
import com.sls.nzdapplication.myapp.ZDAPP;
import com.sls.nzdapplication.tiandimap.TianDiTuMethodsClass;
import com.sls.nzdapplication.ui.custom.AddBdzView;
import com.sls.nzdapplication.ui.custom.AddDLSView;
import com.sls.nzdapplication.ui.custom.AddDlqView;
import com.sls.nzdapplication.ui.custom.AddDxgView;
import com.sls.nzdapplication.ui.custom.AddDzView;
import com.sls.nzdapplication.ui.custom.AddGybView;
import com.sls.nzdapplication.ui.custom.AddgyyhdView;
import com.sls.nzdapplication.ui.custom.AddwkzbView;
import com.sls.nzdapplication.ui.custom.GPSView;
import com.sls.nzdapplication.ui.custom.MapLayer;
import com.sls.nzdapplication.ui.custom.MapLayerView;
import com.sls.nzdapplication.ui.custom.MoreIconView;
import com.sls.nzdapplication.util.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutionException;

import es.dmoral.toasty.Toasty;

/**
 * 这是一个地图展示类，主要功能是展示地图，定位，添加图层，添加设备等。
 * 其中使用了ArcGIS地图SDK，通过调用SDK的方法实现地图的展示，定位等功能。
 * 同时，该类还实现了GPSView.OnGPSViewClickListener, View.OnClickListener, MapLayerView.OnMapLayerListener, MapLayer.MapLayerClickEvent等接口，
 * 实现了对GPSView，MapLayerView等控件的监听。
 */
public class ZyMapActivity extends AppCompatActivity implements GPSView.OnGPSViewClickListener, View.OnClickListener, MapLayerView.OnMapLayerListener, MapLayer.MapLayerClickEvent {
    private GraphicsOverlay graphicsOverlay;

    private GraphicsOverlay lineGraphicOverlay;

    private LocationDisplay mlocationDisplay;

    private MapView mMapView;

    private LocationDisplay mLocationDisplay;

    private final static String TAG = "arcgisMap";

    private AddBdzView addBdzView;

    private AddDxgView addDxgView;

    private AddDlqView addDlqView;

    private AddDzView addDzView;

    private AddGybView addGybView;

    private AddgyyhdView addgyyhdView;

//    private AddwkzbView addwkzbView;

    private String lineId;
    private String lineName;
    private Equipment clickEquipment;

    private EquipmentUtil equipmentUtil;

    private EquipmentLineUtil equipmentLineUtil;

    private AddDLSView addDLSView;

    private MoreIconView moreIconView;

    private MapLayerView mapLayerView;

    private ImageView centerPointView;
    private TextView qdEquipment;


    private MapLayer mapLayer;

    private DrawerLayout drawerLayout;

    private JSONObject clickEquipmentjs = new JSONObject();

    private GPSView mGpsView;

    private GyyhdUtil gyyhdUtil;
    private FileOutputStream outputStream;
    private String equipmentId;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zy_map);
        mMapView = findViewById(R.id.map_view);
        WebTiledLayer webTiledLayer = TianDiTuMethodsClass.CreateTianDiTuTiledLayer(TianDiTuMethodsClass.LayerType.TIANDITU_VECTOR_2000);
        Basemap tdtBasemap = new Basemap(webTiledLayer);
        WebTiledLayer webTiledLayer1 = TianDiTuMethodsClass.CreateTianDiTuTiledLayer(TianDiTuMethodsClass.LayerType.TIANDITU_VECTOR_ANNOTATION_CHINESE_2000);

        // 将天地图的注释图层添加到背景图层中
        tdtBasemap.getBaseLayers().add(webTiledLayer1);

        // 设置ArcGISRuntime的许可证
        ArcGISRuntimeEnvironment.setLicense("runtimelite,1000,rud4449636536,none,NKMFA0PL4S0DRJE15166");
        // 隐藏地图的版权信息
        mMapView.setAttributionTextVisible(false);
        // 创建ArcGISMap对象并使用天地图作为底图
        ArcGISMap map = new ArcGISMap(tdtBasemap);
        // 将地图设置到地图视图中
        mMapView.setMap(map);


        //地图中开启定位
        startLocation();
        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mMapView) {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                //获取屏幕点击坐标
                android.graphics.Point mapPoint = new android.graphics.Point((int) e.getX(), (int) e.getY());
                //将屏幕坐标 传入 identifyGraphicsOverlaysAsync （屏幕坐标，范围，包括图形和弹出窗口时为false，最大检索数）
                final ListenableFuture<List<IdentifyGraphicsOverlayResult>> listListenableFuture = this.mMapView.identifyGraphicsOverlaysAsync(mapPoint, 12, false, 1);
                //添加点击事件
                listListenableFuture.addDoneListener(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //获取点击的范围列表
                            List<IdentifyGraphicsOverlayResult> identifyLayerResults = listListenableFuture.get();
                            //循环图层
                            for (IdentifyGraphicsOverlayResult identifyLayerResult : identifyLayerResults) {
                                //循环所点击要素
                                for (final GeoElement geoElement : identifyLayerResult.getGraphics()) {
                                    if (geoElement.getGeometry().getGeometryType().toString().equals("POINT") && !geoElement.getAttributes().get("type").equals("高压用户点")) {
                                        Log.e(TAG, "当前点击的" + geoElement.getAttributes());
                                        clickEquipmentjs = new JSONObject();
                                        clickEquipmentjs.put("id", geoElement.getAttributes().get("id").toString());
                                        clickEquipmentjs.put("title", geoElement.getAttributes().get("title").toString());
                                        clickEquipmentjs.put("name", geoElement.getAttributes().get("name").toString());
                                        clickEquipmentjs.put("type", geoElement.getAttributes().get("type").toString());
                                        clickEquipment = equipmentUtil.listOneEquipment(geoElement.getAttributes().get("id").toString());
                                        qdEquipment.setText("当前设备：" + clickEquipment.getName() + "【点击查看详情】");
                                    } else if (geoElement.getGeometry().getGeometryType().toString().equals("POINT") && geoElement.getAttributes().get("type").equals("高压用户点")) {
                                        Log.e(TAG, "当前点击的" + geoElement.getAttributes());
                                        clickEquipmentjs = new JSONObject();
                                        clickEquipmentjs.put("id", geoElement.getAttributes().get("id").toString());
                                        clickEquipmentjs.put("title", geoElement.getAttributes().get("title").toString());
                                        clickEquipmentjs.put("name", geoElement.getAttributes().get("name").toString());
                                        clickEquipmentjs.put("type", geoElement.getAttributes().get("type").toString());
//                                        clickEquipment = equipmentUtil.listOneEquipment(geoElement.getAttributes().get("id").toString());
                                        qdEquipment.setText("当前设备：" + geoElement.getAttributes().get("name").toString() + "【点击查看详情】");
                                    }
                                }
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                    }
                });
                return super.onSingleTapUp(e);
            }
        });
        initView();
        initListener();

    }

    @Override
    protected void onStart() {
        super.onStart();
        initData();
    }

    private void startLocation() {
        mLocationDisplay = mMapView.getLocationDisplay();
        mLocationDisplay.setAutoPanMode(LocationDisplay.AutoPanMode.RECENTER);
        //当我们执行LocationDisplay.startAsync()方法时候，会在地图上显示出我们当前位置
        mLocationDisplay.startAsync();

        //获取的点是基于当前地图坐标系的点
        Point point = mLocationDisplay.getMapLocation();
        Log.e("xyh", "point: " + point.toString());

        //获取基于GPS的位置信息
        LocationDataSource.Location location = mLocationDisplay.getLocation();
        //基于WGS84的经纬度坐标。
        Point point1 = location.getPosition();
        if (point1 != null) {
            Log.e("xyh", "point1: " + point1.toString());
        }

        //如果要在LocationDisplay里进行位置信息的自动监听，方法也很简单，只需要LocationDisplay.addLocationChangedListener即可
        mLocationDisplay.addLocationChangedListener(new LocationDisplay.LocationChangedListener() {
            @Override
            public void onLocationChanged(LocationDisplay.LocationChangedEvent locationChangedEvent) {
                LocationDataSource.Location location = locationChangedEvent.getLocation();
                Geocoder geocoder = new Geocoder(getApplicationContext());

                List<Address> addresses = null;
                try {
                    // 尝试根据位置的经纬度获取地址信息
                    addresses = geocoder.getFromLocation(location.getPosition().getY(), location.getPosition().getX(), 1);
                } catch (IOException e) {
                    // 处理地理编码时可能出现的IO异常
                    e.printStackTrace();
                }
                if (!addresses.isEmpty()) {
                    // 如果成功获取地址信息，将其保存到SharedPreferences
                    new MySharedPreferences(getApplicationContext()).saveAddress(addresses.get(0).getAddressLine(0));
                }
//                try {
//                    new MySharedPreferences(getApplicationContext()).saveAddress(geocoder.getFromLocation(location.getPosition().getY(), location.getPosition().getX(), 1).get(0).getAddressLine(0));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        if (view == addBdzView) {
            if (equipmentUtil.queryEquipmentByLineId(lineId).size() > 0) {
                Toasty.info(getApplicationContext(), "该线路已存在变电站", Toast.LENGTH_SHORT, true).show();
                return;
            }
            newEquipment(ZDAPP.EQUIPMENT_BDZ);
            return;
        }
        if (view == addDxgView) {
            if (equipmentUtil.queryEquipmentByLineId(lineId).size() == 0) {
                Toasty.info(getApplicationContext(), "请先新建变电站", Toast.LENGTH_SHORT, true).show();
                return;
            }
            newEquipment(ZDAPP.EQUIPMENT_DXG);
            return;
        }
        if (view == addDlqView) {
            if (equipmentUtil.queryEquipmentByLineId(lineId).size() == 0) {
                Toasty.info(getApplicationContext(), "请先新建变电站", Toast.LENGTH_SHORT, true).show();
                return;
            }
            newEquipment(ZDAPP.EQUIPMENT_DLQ);
            return;
        }
        if (view == addDzView) {
            if (equipmentUtil.queryEquipmentByLineId(lineId).size() == 0) {
                Toasty.info(getApplicationContext(), "请先新建变电站", Toast.LENGTH_SHORT, true).show();
                return;
            }
            newEquipment(ZDAPP.EQUIPMENT_DZ);
            return;
        }
        if (view == addGybView) {
            if (equipmentUtil.queryEquipmentByLineId(lineId).size() == 0) {
                Toasty.info(getApplicationContext(), "请先新建变电站", Toast.LENGTH_SHORT, true).show();
                return;
            }
            newEquipment(ZDAPP.EQUIPMENT_GYB);
            return;
        }
        if (view == addDLSView) {
            if (equipmentUtil.queryEquipmentByLineId(lineId).size() == 0) {
                Toasty.info(getApplicationContext(), "请先新建变电站", Toast.LENGTH_SHORT, true).show();
                return;
            }
            newEquipment("跌落式熔断器");
            return;
        }
        if (view == addgyyhdView) {
            Point point = getMapCenterPoint();
            Intent intent = new Intent(ZyMapActivity.this, GyyhdActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("type", "高压用户点");
            bundle.putString("lineId", lineId);
            bundle.putBoolean("new", true);
            bundle.putDouble("lat", point.getY());
            bundle.putDouble("lon", point.getX());
            bundle.putString("clickE", clickEquipment == null ? "" : clickEquipment.getId());
            intent.putExtra("params", bundle);
            startActivity(intent);
        }

        if (view == moreIconView) {
            Intent intent = new Intent(ZyMapActivity.this, ZyManagementActivity.class);
            intent.putExtra("lineId", lineId);
            startActivity(intent);
        }
        if (view == qdEquipment) {
            if (clickEquipmentjs.containsKey("type") && !clickEquipmentjs.getString("type").equals("高压用户点")) {
                Intent intent = new Intent(ZyMapActivity.this, EquipmentActivity.class);
                intent.putExtra("equipmentId", clickEquipmentjs.getString("id"));
                startActivity(intent);
            } else if (clickEquipmentjs.containsKey("type") && clickEquipmentjs.getString("type").equals("高压用户点")) {
                Intent intent = new Intent(ZyMapActivity.this, GyyhdActivity.class);
                intent.putExtra("equipmentId", clickEquipmentjs.getString("id"));
                startActivity(intent);
            } else {

            }
        }

        //获取屏幕四个角坐标位点
//        if (view == addwkzbView) {
//            new PopWindow.Builder(ZyMapActivity.this)
//                    .setStyle(PopWindow.PopWindowStyle.PopUp)
//                    .setTitle("获取线路范围图标")
//                    .addItemAction(new PopItemAction("确定", PopItemAction.PopItemStyle.Warning, new PopItemAction.OnClickListener() {
//                        @Override
//                        public void onClick() {
//                            // 获取屏幕尺寸
//                            DisplayMetrics displayMetrics = new DisplayMetrics();
//                            getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
//                            int screenWidth = displayMetrics.widthPixels;
//                            int screenHeight = displayMetrics.heightPixels;
//
//                            // 创建代表屏幕边缘位置的点
//                            android.graphics.Point topLeftScreenPoint = new android.graphics.Point(0, 0);
//                            android.graphics.Point topRightScreenPoint = new android.graphics.Point(screenWidth, 0);
//                            android.graphics.Point bottomLeftScreenPoint = new android.graphics.Point(0, screenHeight);
//                            android.graphics.Point bottomRightScreenPoint = new android.graphics.Point(screenWidth, screenHeight);
//
//                            // 转换屏幕上的四个角点到地图坐标
//                            Point topLeftMapPoint = mMapView.screenToLocation(topLeftScreenPoint);
//                            Point topRightMapPoint = mMapView.screenToLocation(topRightScreenPoint);
//                            Point bottomLeftMapPoint = mMapView.screenToLocation(bottomLeftScreenPoint);
//                            Point bottomRightMapPoint = mMapView.screenToLocation(bottomRightScreenPoint);
//
//                            // 格式化地图坐标为保留八位小数的字符串
//                            String topLeftFormatted = formatPoint(topLeftMapPoint);
//                            String topRightFormatted = formatPoint(topRightMapPoint);
//                            String bottomLeftFormatted = formatPoint(bottomLeftMapPoint);
//                            String bottomRightFormatted = formatPoint(bottomRightMapPoint);
//
//                            // 格式化四个坐标点的数据为一个字符串
//                            String coordinatesString = "左上: " + topLeftFormatted + "\n"
//                                    + "右上: " + topRightFormatted + "\n"
//                                    + "左下: " + bottomLeftFormatted + "\n"
//                                    + "右下: " + bottomRightFormatted;
//
//                            //将当前的线路名称设置给txt文件
//                            String filename = "/"+lineName+".txt";
//                            try {
//                                // 检查是否有写外部存储的权限
//                                if (ContextCompat.checkSelfPermission(ZyMapActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                                        != PackageManager.PERMISSION_GRANTED) {
//                                    // 如果没有权限，请求权限
//                                    ActivityCompat.requestPermissions(ZyMapActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
//                                } else {
//                                    // 获取外部存储的公共目录
//                                    File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
//
//                                    // 如果目录不存在，则创建它
//                                    if (!dir.exists()) {
//                                        dir.mkdirs();
//                                    }
//                                    // 创建文件路径
//                                    File file = new File(dir,filename);
//                                    outputStream = new FileOutputStream(file);
//                                    outputStream.write(coordinatesString.getBytes());
//                                    Toasty.success(getApplicationContext(), "导出成功", Toast.LENGTH_LONG, true).show();
//                                }
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    }))
//                    .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Cancel))
//                    .show();
//        }

    }

    private String formatPoint(Point point) {
        if (Double.isNaN(point.getX()) || Double.isNaN(point.getY())) {
            return "Invalid point";
        } else {
            return String.format("%.8f, %.8f", point.getX(), point.getY());
        }
    }

    private void initView() {
        addBdzView = findViewById(R.id.add_bdz);
        addDxgView = findViewById(R.id.add_dxg);
        addDlqView = findViewById(R.id.add_dlq);
        addDzView = findViewById(R.id.add_dz);
        addGybView = findViewById(R.id.add_gyb);
        addDLSView = findViewById(R.id.add_dls);
        addgyyhdView = findViewById(R.id.add_gyyhd);

//        addwkzbView = findViewById(R.id.add_wkzb);

        centerPointView = findViewById(R.id.center_point);
        mapLayer = findViewById(R.id.map_layer_view);
        qdEquipment = findViewById(R.id.qd_equipment);

        moreIconView = findViewById(R.id.miv);
        mapLayerView = findViewById(R.id.mv);
        drawerLayout = findViewById(R.id.drawer_layout);
        mapLayer.setMapLayerClickEvent(this);
        mGpsView = (GPSView) findViewById(R.id.gps_view);
        mGpsView.setOnGPSViewClickListener(this);
    }

    /**
     * 初始化数据的方法。
     * 该方法从传入的Intent中提取"lineId"作为字符串，然后执行ZyMapActivity.InitOverTask任务。
     */
    private void initData() {
        // 从Intent中获取传入的"lineId"
        Intent intent = getIntent();
        lineId = intent.getStringExtra("lineId");
        lineName = intent.getStringExtra("lineName");
        // 执行ZyMapActivity.InitOverTask异步任务
        new ZyMapActivity.InitOverTask().execute();
    }

    private void initListener() {
        addBdzView.setOnClickListener(this);
        addDxgView.setOnClickListener(this);
        addDlqView.setOnClickListener(this);
        addDzView.setOnClickListener(this);
        addGybView.setOnClickListener(this);
        addDLSView.setOnClickListener(this);
        moreIconView.setOnClickListener(this);
        addgyyhdView.setOnClickListener(this);

        mapLayerView.setOnMapLayerListener(this);
        moreIconView.setOnClickListener(this);
        qdEquipment.setOnClickListener(this);
//        addwkzbView.setOnClickListener(this);
        mapLayerView.setOnMapLayerListener(this);
        equipmentUtil = new EquipmentUtil(getApplicationContext());
        equipmentLineUtil = new EquipmentLineUtil(getApplicationContext());
        gyyhdUtil = new GyyhdUtil(getApplicationContext());
    }


    @Override
    protected void onPause() {
        super.onPause();
        mMapView.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.resume();
        new ZyMapActivity.InitOverTask().execute();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.dispose();
    }

    @Override
    public void openMapLayer(String type) {
        if (type.equals("default")) {

            WebTiledLayer webTiledLayer = TianDiTuMethodsClass.CreateTianDiTuTiledLayer(TianDiTuMethodsClass.LayerType.TIANDITU_VECTOR_2000);
            Basemap tdtBasemap = new Basemap(webTiledLayer);
            WebTiledLayer webTiledLayer1 = TianDiTuMethodsClass.CreateTianDiTuTiledLayer(TianDiTuMethodsClass.LayerType.TIANDITU_VECTOR_ANNOTATION_CHINESE_2000);
            tdtBasemap.getBaseLayers().add(webTiledLayer1);

            ArcGISMap map = new ArcGISMap(tdtBasemap);
            mMapView.setMap(map);
            centerPointView.setBackgroundResource(R.drawable.center_point);
            startLocation();
        } else {
            WebTiledLayer webTiledLayer2 = TianDiTuMethodsClass.CreateTianDiTuTiledLayer(TianDiTuMethodsClass.LayerType.TIANDITU_IMAGE_2000);
            Basemap tdtBasemap2 = new Basemap(webTiledLayer2);
            WebTiledLayer webTiledLayer22 = TianDiTuMethodsClass.CreateTianDiTuTiledLayer(TianDiTuMethodsClass.LayerType.TIANDITU_IMAGE_ANNOTATION_CHINESE_2000);
            tdtBasemap2.getBaseLayers().add(webTiledLayer22);

            ArcGISMap map = new ArcGISMap(tdtBasemap2);
            mMapView.setMap(map);

            centerPointView.setBackgroundResource(R.drawable.center_yellow);
            startLocation();
        }
    }

/**
 * 新增设备的函数。
 * 根据传入的设备类型，判断当前是否已选择了特定类型的设备（高压用户点），若已选择，则提示重新选择设备并终止操作；
 * 若未选择，则获取当前地图中心点，准备跳转到设备选择界面。
 *
 * @param type 设备类型，用于在新增设备界面中确定要添加的设备种类。
 */
private void newEquipment(String type) {
    // 检查是否已选择了“高压用户点”类型的设备，若已选择，则提示重新选择并返回
    if (clickEquipmentjs.containsKey("type") && clickEquipmentjs.getString("type").equals("高压用户点")) {
        Toasty.info(getApplicationContext(), "请重新选择前端设备", Toast.LENGTH_SHORT, true).show();
        return;
    } else {
        // 获取当前地图的中心点
        Point point = getMapCenterPoint();
        // 构造跳转到设备选择界面的Intent，并准备必要参数
        Intent intent = new Intent(ZyMapActivity.this, EquipmentActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        // 准备设备选择界面需要的参数，包括设备类型、线路ID、是否为新增设备、地图中心点的经纬度、上一次点击的设备ID等
        bundle.putString("lineId", lineId);
        bundle.putBoolean("new", true);
        bundle.putDouble("lat", point.getY());
        bundle.putDouble("lon", point.getX());
        bundle.putString("clickE", clickEquipment == null ? "" : clickEquipment.getId());
        // 将参数Bundle放入Intent中
        intent.putExtra("params", bundle);
        // 启动跳转
        startActivity(intent);
    }

}


    /**
     * func:获取屏幕中心的经纬度坐标
     *
     * @return 经纬度
     */
    public Point getMapCenterPoint() {
        int left = mMapView.getLeft();
        int top = mMapView.getTop();
        int right = mMapView.getRight();
        int bottom = mMapView.getBottom();
        // 获得屏幕点击的位置
        int x = (int) (mMapView.getX() + (right - left) / 2);
        int y = (int) (mMapView.getY() + (bottom - top) / 2);
        return mMapView.screenToLocation(new android.graphics.Point(x, y));
    }

    @Override
    public void openOverLayer(List<String> actives) {

    }

    @Override
    public void openofflineMap() {

    }

    @Override
    public void onMapLayerClick() {
        drawerLayout.openDrawer(Gravity.RIGHT);
    }

    private void initOverLayer() {
//        graphicsOverlay.getGraphics().clear();
        mMapView.getGraphicsOverlays().clear();
        initEquipment();
        initChannel();

        System.err.println(graphicsOverlay.getGraphics().size());

    }

    private void initEquipment() {
        List<Equipment> equipmentList = equipmentUtil.queryEquipmentByLineId2(lineId);
        addEquipmentMarkPoint(equipmentList, R.drawable.bdzmap);
    }


    private void addEquipmentMarkPoint(List<Equipment> equipmentList, int drawable) {
        graphicsOverlay = new GraphicsOverlay(GraphicsOverlay.RenderingMode.STATIC);
        for (Equipment equipment : equipmentList) {
            if (null != equipment.getLat()) {

                try {
                    drawable = ZDAPP.EquipmentMapDrawable.get(equipment.getType());
                    Bitmap bitmap = Utils.getMardBitmap(equipment.getName(), drawable, getApplicationContext());
                    PictureMarkerSymbol simpleMarkerSymbol = new PictureMarkerSymbol(new BitmapDrawable(bitmap));
                    float offset = Float.valueOf(bitmap.getWidth()) / Float.valueOf(bitmap.getHeight());
//                    simpleMarkerSymbol.setOffsetX((offset*(4.7f+offset/15f))*(float)1.3888);
                    simpleMarkerSymbol.setOffsetX((offset * (4.7f + offset / 15f)) * (float) 0.92);
                    simpleMarkerSymbol.setOffsetY(7f);
                    Graphic graphic = new Graphic(new Point(equipment.getLon(), equipment.getLat()), simpleMarkerSymbol);
                    graphic.getAttributes().put("title", equipment.getType());
                    graphic.getAttributes().put("id", equipment.getId());
                    graphic.getAttributes().put("name", equipment.getName());
                    graphic.getAttributes().put("type", equipment.getType());
                    graphicsOverlay.getGraphics().add(graphic);
//                    simpleMarkerSymbol.loadAsync();
//                    simpleMarkerSymbol.addDoneLoadingListener(new Runnable() {
//                        @Override
//                        public void run() {
//
//                        }
//                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        List<Gyyhd> gyyhds = gyyhdUtil.queryGyyhdByLineId(lineId);
        for (Gyyhd gyyhd : gyyhds) {
            if (null != gyyhd.getName()) {
                try {
                    drawable = ZDAPP.EquipmentMapDrawable.get(gyyhd.getType());
                    Bitmap bitmap = Utils.getMardBitmap(gyyhd.getName(), drawable, getApplicationContext());
                    PictureMarkerSymbol simpleMarkerSymbol = new PictureMarkerSymbol(new BitmapDrawable(bitmap));
                    float offset = Float.valueOf(bitmap.getWidth()) / Float.valueOf(bitmap.getHeight());
//                    simpleMarkerSymbol.setOffsetX((offset*(4.7f+offset/15f))*(float)1.3888);
                    simpleMarkerSymbol.setOffsetX((offset * (4.7f + offset / 15f)) * (float) 0.92);
                    simpleMarkerSymbol.setOffsetY(7f);
                    Graphic graphic = new Graphic(new Point(gyyhd.getLon(), gyyhd.getLat()), simpleMarkerSymbol);
                    graphic.getAttributes().put("title", gyyhd.getType());
                    graphic.getAttributes().put("id", gyyhd.getId());
                    graphic.getAttributes().put("name", gyyhd.getName());
                    graphic.getAttributes().put("type", gyyhd.getType());
                    graphicsOverlay.getGraphics().add(graphic);
//                    simpleMarkerSymbol.loadAsync();
//                    simpleMarkerSymbol.addDoneLoadingListener(new Runnable() {
//                        @Override
//                        public void run() {
//
//                        }
//                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        mMapView.getGraphicsOverlays().add(graphicsOverlay);
    }

    public void initChannel() {

        // 创建一个图形覆盖物并设置其渲染模式为静态
        lineGraphicOverlay = new GraphicsOverlay(GraphicsOverlay.RenderingMode.STATIC);

        // 根据线路ID查询设备线路信息
        List<EquipmentLine> equipmentLines = equipmentLineUtil.queryEquipmentLineByLineId(lineId);
        // 遍历查询到的设备线路信息
        for (EquipmentLine equipmentLine : equipmentLines) {
            try {
                // 创建一个简单线条符号，设置线条样式、颜色和宽度
                SimpleLineSymbol simpleLineSymbol;
                //根据连接方式设置不同的颜色 架空黄 入地红
               if (equipmentLine.getType().equals("2")){
                    simpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.parseColor("#FF9912"), 2);
               }else {
                   simpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.parseColor("#FF0000"), 2);
               }

                // 创建多段线构建器并设置其空间参考
                PolylineBuilder lineGeometry = new PolylineBuilder(SpatialReferences.getWgs84());

                // 根据设备线路的起始和终止设备ID查询并添加设备位置点
                Equipment s = equipmentUtil.listOneEquipment(equipmentLine.getStartEquipmentId());
                Equipment e = equipmentUtil.listOneEquipment(equipmentLine.getEndEquipmentId());
                lineGeometry.addPoint(new Point(s.getLon(), s.getLat()));
                lineGeometry.addPoint(new Point(e.getLon(), e.getLat()));

                // 创建图形对象，并将其添加到图形覆盖物中
                Graphic lineGraphic = new Graphic(lineGeometry.toGeometry(), simpleLineSymbol);
                lineGraphicOverlay.getGraphics().add(lineGraphic);
            } catch (Exception e) {
                // 异常处理，打印堆栈跟踪信息
                e.printStackTrace();
            }
        }

        // 将图形覆盖物添加到地图视图中
        mMapView.getGraphicsOverlays().add(lineGraphicOverlay);
    }

    @Override
    public void onGPSClick() {
        startLocation();
    }

//    @Override
//    public boolean isBaseOnWidth() {
//        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
//            return true;//根据宽度适配
//        } else {
//            return false;//根据高度适配
//        }
//    }
//
//    @Override
//    public float getSizeInDp() {
//        // 横屏下的高度不就是竖屏的宽度吗,所以统一返回宽度即可
//        return 500;
//    }


    class InitOverTask extends AsyncTask<Void, Integer, Boolean> {

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected Boolean doInBackground(Void... params) {
            initOverLayer();
            return true;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {

        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                List<Equipment> equipmentList = equipmentUtil.queryEquipmentByLineId2(lineId);
                if (equipmentList.size() > 0) {
                    clickEquipment = equipmentList.get(0);
                    clickEquipmentjs = new JSONObject();
                    clickEquipmentjs.put("id", clickEquipment.getId());
                    clickEquipmentjs.put("title", clickEquipment.getType());
                    clickEquipmentjs.put("type", clickEquipment.getType());
                    clickEquipmentjs.put("name", clickEquipment.getName());
                    qdEquipment.setText("当前设备：" + clickEquipment.getName() + "【点击查看详情】");
                } else {
                    clickEquipment = null;
                    clickEquipmentjs = new JSONObject();
                    qdEquipment.setText("当前设备:");
                }
            }
        }
    }
}